package com.haochang.chunkvod.view.vod.flavor;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * @author qintao
 * created at 2016/6/18 14:06
 * 自适应高度的viewgrooup
 */

public class flavorViewGroup extends ViewGroup
{

	private final static int VIEW_MARGIN = 10;

	public flavorViewGroup(Context context)
	{
		super(context);
	}

	public flavorViewGroup(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
	}

	public flavorViewGroup(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		int stages = 1;
		int stageHeight = 0;
		int stageWidth = 0;
		int wholeWidth = MeasureSpec.getSize(widthMeasureSpec);

		for (int i = 0; i < getChildCount(); i++)
		{
			final View child = getChildAt(i);
			// measure
			measureChild(child, widthMeasureSpec, heightMeasureSpec);
			stageWidth += (child.getMeasuredWidth() + VIEW_MARGIN);
			stageHeight = child.getMeasuredHeight();
			if (stageWidth >= wholeWidth)
			{
				stages++;
				// reset stageWidth
				stageWidth = child.getMeasuredWidth();
			}
		}

		int wholeHeight = (stageHeight + VIEW_MARGIN) * stages + VIEW_MARGIN;
		// report this final dimension
		setMeasuredDimension(resolveSize(wholeWidth, widthMeasureSpec), resolveSize(wholeHeight, heightMeasureSpec));

	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b)
	{
		final int count = getChildCount();
		int row = 0; // which row lay your view relative to parent
		int lengthX = l; // right position of child relative to parent
		int lengthY = t; // bottom position of child relative to parent

		for (int i = 0; i < count; i++)
		{
			final View child = this.getChildAt(i);
			int width = child.getMeasuredWidth();
			int height = child.getMeasuredHeight();

			lengthX += width + VIEW_MARGIN;
			lengthY = row * (height + VIEW_MARGIN) + VIEW_MARGIN + height + t;

			// if it cant't draw in a same line ,skip it to next line
			if (lengthX > r)
			{
				lengthX = width + VIEW_MARGIN + l;
				row++;
				lengthY = row * (height + VIEW_MARGIN) + VIEW_MARGIN + height + t;
			}
			child.layout(lengthX - width, lengthY - height, lengthX, lengthY);
		}
	}

}